package com.jjh.controller;

import com.alibaba.fastjson.JSONObject;
import com.jjh.pojo.Players;
import com.jjh.pojo.UserPicture;
import com.jjh.service.PictureService;
import com.jjh.service.PlayerService;
import com.jjh.service.UserService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 点击参加比赛后的，上传的图片
 */
@Controller
public class UserController {

    @Autowired
    PlayerService playerService;
    @RequestMapping(value ="/uploadFile",method = RequestMethod.POST)

    public String addUser(HttpServletRequest request)
            throws IOException, InvocationTargetException, IllegalAccessException, FileUploadException {

        // 先实例化一个文件解析器
        CommonsMultipartResolver coMultiResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());

        MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;

//        String openId = "12312"/*request.getParameter("openid")*/;//如果拿不到尝试getAttribute()方法
        String openId = (String) request.getSession().getAttribute("openid");
        List<MultipartFile> photos = params.getFiles("picture");
        List<UserPicture> pictures = new ArrayList<>();


        String basepath = File.separator+"img"+File.separator;
        String basepath1= File.separator+"image"+File.separator;

        //根据日期 每天创建新的文件夹
        Date date = new Date();

        basepath = basepath + new SimpleDateFormat("yyyyMMdd").format(date);
        basepath1 = basepath1 + new SimpleDateFormat("yyyyMMdd").format(date);

        String storePath = request.getSession().getServletContext().getRealPath(basepath);
        String storePath1 =  request.getSession().getServletContext().getRealPath(basepath1);
        System.out.println(storePath);
        File storeDirectory = new File(storePath);
        File stroreDirectory1 = new File(storePath1);
        if (!storeDirectory.exists()) {
            storeDirectory.mkdirs();
        }
        if (!stroreDirectory1.exists()) {
            stroreDirectory1.mkdirs();
        }
        for (MultipartFile photo : photos) {
            if (!photo.isEmpty()) {
                //获得原始文件名
                String fileName = photo.getOriginalFilename();
                UserPicture picture = new UserPicture();
                //获取文件名后缀
                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                System.out.println("原始文件名: " + fileName);
                //字符串转换
                String newName = System.currentTimeMillis() + String.valueOf(fileF);
                File filePhoto = new File(storePath, newName);
                File filePhoto1 = new File(storePath1,newName);
                //保存图片
                photo.transferTo(filePhoto);
                //文件处理
                Thumbnails.of(filePhoto).scale(1f).outputQuality(0.3f).toFile(filePhoto1);

                //最终存储的图片地址
                String savePath = basepath1 + File.separator + newName;
                picture.setOpenid(openId);
                picture.setPicture(savePath);
                pictures.add(picture);

            }

        }
        String college = params.getParameter("Institute");
        String stu_num = params.getParameter("stuId");//学号
        String stu_name = params.getParameter("name");//团队名称||以毕业校友名称
        String tel = params.getParameter("phoneNum");
        String pic_introduce = params.getParameter("picIntroduction");//图片介绍
        String datetime = request.getParameter("time");//链接时间
        String picture1 = pictures.get(0).getPicture();//第一张图片链接地址
        String onSchool = params.getParameter("identity");
        Players user = new Players();
        user.setOpenid(openId);
        user.setCollege(college);
        user.setStuNum(stu_num);
        user.setStuName(stu_name);
        user.setTel(tel);
        user.setPicIntroduce(pic_introduce);
        user.setDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
        user.setPicture(picture1);
        user.setIsinsite(Integer.valueOf(onSchool));
        playerService.insertPlayer(user,pictures);
        return "redirect:/byj/succee.html";
    }

}
